package com.example.mynewsapp.fragment.news_history_favor

import android.app.Activity
import android.app.AlertDialog
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mynewsapp.R
import com.example.mynewsapp.activity.DetailNews
import com.example.mynewsapp.adapter.NewsAdapter
import com.example.mynewsapp.fragment.Fragment.db
import com.example.mynewsapp.fragment.Fragment.mActivity
import com.example.mynewsapp.fragment.Fragment.news_adapter
import com.example.mynewsapp.model.NewsItem
import kotlinx.android.synthetic.main.delete_dialog.view.*
import kotlinx.android.synthetic.main.news_view.*

abstract class FragmentNewsHisandFavor : Fragment() {

    abstract fun getTableName() :String

    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.news_view, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recycler_view.setLayoutManager(LinearLayoutManager(context))
        recycler_view.setHasFixedSize(true)
        recycler_view.hideShimmerAdapter()
        newsList.setVisibility(View.GONE)

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        generateDummyList()

        down_pull_update.setColorSchemeResources(R.color.colorPrimaryDark)
        down_pull_update.setOnRefreshListener {
            var handler = Handler()
            handler.postDelayed({
                generateDummyList()
                down_pull_update.isRefreshing = false
                refreshSuccess()
            }, 1000)
        }
    }

    private fun generateDummyList() {

        val list = ArrayList<NewsItem>()
        val cursor = db!!.query(getTableName(), null, null, null, null, null, null)

        while (cursor.moveToNext()) {

            val drawable = cursor.getString(cursor.getColumnIndex("newsImage"))
            val update = cursor.getString(cursor.getColumnIndex("newsUpdate"))
            val ctry = cursor.getString(cursor.getColumnIndex("newsCountry"))
            val title = cursor.getString(cursor.getColumnIndex("newsTitle"))
            val date = cursor.getString(cursor.getColumnIndex("newsDate"))
            val url = cursor.getString(cursor.getColumnIndex("newsUrl"))

            var like  = ""
            if (getTableName() == "history") {
                like = "no"
                val cursor1 = db!!.query("favorite", null, null, null, null, null, null)
                while (cursor1.moveToNext()) {
                    val url_db = cursor1.getString(cursor1.getColumnIndex("newsUrl"))
                    if (url_db == url) {
                        like = "yes"
                        break
                    }
                }
            } else {
                like = cursor.getString(cursor.getColumnIndex("newsLike"))
            }

            val item = NewsItem(drawable, update, ctry, title, date, url, like)
            list += item
        }
        cursor.close() // 关闭游标，释放资源
        if (list.isEmpty()) {
            onSetList(list)
            tips()
        } else {
            onSetList(sortList(list))
        }

    }

    private fun sortList(list: ArrayList<NewsItem>): ArrayList<NewsItem> {
        val arr = ArrayList<NewsItem>()
        var length = list.size - 1
        while (length >= 0) {
            arr += list[length]
            length--
        }
        return arr
    }

    // 设置列表
    private fun onSetList(list: ArrayList<NewsItem>) {

        if (recycler_view == null) return

        recycler_view.layoutManager = LinearLayoutManager(context)
        news_adapter = NewsAdapter(list!!, context!!)
        recycler_view.adapter = news_adapter
        news_adapter!!.notifyDataSetChanged()
        recycler_view.hideShimmerAdapter()
        newsList.visibility = View.VISIBLE

        news_adapter?.mOnRecyclerViewItemClick = object :
                NewsAdapter.OnRecyclerViewItemClick {
            override fun OnItemClick(view: View?, content: NewsItem, position: Int) {
                val intent = Intent(context, DetailNews::class.java)

                ifNewsExist(content)
                addData(content)

                intent.putExtra(DetailNews.DETAIL_NEWS, content)
                startActivity(intent)
            }

            override fun OnLongClick(view: View?, content: NewsItem, position: Int) {
                val dialogView = LayoutInflater.from(mActivity).inflate(R.layout.delete_dialog, null)
                val builder = AlertDialog.Builder(mActivity)
                        .setView(dialogView)
                        .setTitle(R.string.deleteFavorTitle)
                val alertDialog = builder.show()

                dialogView.delete_dialog.setText(R.string.deleteFavorite)
                dialogView.delete_cancel.setText(R.string.cancelBtn)
                dialogView.delete_confirm.setText(R.string.confirmBtn)

                dialogView.delete_confirm.setOnClickListener {
                    alertDialog.dismiss()
                    db!!.delete(getTableName(), "newsUrl=?", arrayOf(content.url))
                    generateDummyList()
                }
                dialogView.delete_cancel.setOnClickListener {
                    alertDialog.dismiss()
                }
            }
        }
    }

    private fun addData (content: NewsItem) {
        if (content.url == "") return
        //创建存放数据的ContentValues对象
        val values = ContentValues()
        values.put("newsImage", content.image)
        values.put("newsUpdate", content.update)
        values.put("newsCountry", content.country)
        values.put("newsTitle", content.title)
        values.put("newsDate", content.date)
        values.put("newsUrl", content.url)
        values.put("newsLike", content.like)
        //数据库执行插入命令
        db!!.insert("history", null, values)

    }

    private fun ifNewsExist (content: NewsItem){

        if (content.url == "") return

        val cursor = db!!.query("history", null, null, null, null, null, null)
        while (cursor.moveToNext()) {
            val url = cursor.getString(cursor.getColumnIndex("newsUrl"))
            if (url == content.url) {
                db!!.delete("history","newsUrl=?", arrayOf(url))
                break
            }
        }
        cursor.close() // 关闭游标，释放资源
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as Activity
    }

    private fun tips() {
        if (this.isAdded) {
            Toast.makeText(mActivity, getString(R.string.noFavorite), Toast.LENGTH_SHORT).show()
        }
    }

    private fun refreshSuccess() {
        if (this.isAdded) {
            Toast.makeText(mActivity, getString(R.string.refreshSuccess), Toast.LENGTH_SHORT).show()
        }
    }
}